package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.base.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private WorkBillRepository workBillRepository;
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private FixedAreaRepository fixedAreaRepository;

	@Override
	public void addOrder(Order order) {

		// 设置订单id
		order.setOrderNum(UUID.randomUUID().toString());
		order.setStatus("1");
		order.setOrderTime(new Date());

		// 关联持久态的Area
		Area sendArea = areaRepository.findAreaByProvinceAndCityAndDistrict(
				order.getSendArea().getProvince(), order.getSendArea()
						.getCity(), order.getSendArea().getDistrict());
		Area recArea = areaRepository.findAreaByProvinceAndCityAndDistrict(
				order.getRecArea().getProvince(), order.getRecArea().getCity(),
				order.getRecArea().getDistrict());

		order.setSendArea(sendArea);
		order.setRecArea(recArea);

		/*
		 * 自动下单
		 */
		// 根据详细地址找到定区id
		String fiedAreaId = WebClient
				.create(Constants.CRM_MANAGEMENT_URL
						+ "/services/customerService/findFixedAreaIdByAddress/"
						+ order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);

		if (StringUtils.isNotBlank(fiedAreaId)) {
			// 获取定区
			FixedArea fixedArea = fixedAreaRepository.findOne(fiedAreaId);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()) {
				Courier courier = iterator.next();
				saveOrder(order, courier);
				generateWorkBill(order);
			}
			return;
		}

		// 查看详细地址在哪个分区----->定区---->快递员
		Set<SubArea> subareas = sendArea.getSubareas();
		for (SubArea subArea : subareas) {

			String sendAddress = order.getSendAddress();
			if (sendAddress.contains(subArea.getAssistKeyWords())) {

				FixedArea fixedArea = subArea.getFixedArea();
				Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
				if (iterator.hasNext()) {

					Courier courier = iterator.next();
					saveOrder(order, courier);
					generateWorkBill(order);
					return;
				}
			}
		}

		Set<SubArea> subareas2 = sendArea.getSubareas();
		for (SubArea subArea : subareas2) {

			String sendAddress = order.getSendAddress();
			if (sendAddress.contains(subArea.getKeyWords())) {

				Iterator<Courier> iterator = subArea.getFixedArea()
						.getCouriers().iterator();
				if (iterator.hasNext()) {

					Courier courier = iterator.next();
					saveOrder(order, courier);
					generateWorkBill(order);
					return;
				}
			}
		}
	}

	private void saveOrder(Order order, Courier courier) {

		order.setCourier(courier);
		// 设置自动分单
		order.setOrderType("1");
		orderRepository.save(order);
	}

	// 生成工单，发送短信
	private void generateWorkBill(final Order order) {
		// 生成工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber); // 短信序号
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBillRepository.save(workBill);

		// 发送短信
		// 调用MQ服务，发送一条消息
//		jmsTemplate.send("bos_sms", new MessageCreator() {
//			@Override
//			public Message createMessage(Session session) throws JMSException {
//				MapMessage mapMessage = session.createMapMessage();
//				mapMessage.setString("telephone", order.getCourier()
//						.getTelephone());
//				mapMessage.setString(
//						"msg",
//						"短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress()
//								+ ",联系人:" + order.getSendName() + ",手机:"
//								+ order.getSendMobile() + "，快递员捎话："
//								+ order.getSendMobileMsg());
//				return mapMessage;
//			}
//		});
		// 修改工单状态
		workBill.setPickstate("已通知");
	}

}
